from rest_framework import serializers
from .models import User
from .utils import get_user_by_account
from django.contrib.auth.hashers import make_password
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer


class UserModelSerializer(serializers.ModelSerializer):
    """
    用户信息序列化器
    """
    token = serializers.CharField(max_length=1000, read_only=True, help_text="token认证字符串")

    class Meta:
        model = User
        fields = ["id", "username", "password", "token", "is_superuser"]
        extra_kwargs = {
            "id": {
                "read_only": True,
            },
            "password": {
                "write_only": True,
            }
        }

    def validate(self, attrs):
        username = attrs.get("username")
        password = attrs.get("password")

        # 验证码用户名是否已经被注册过了
        ret = get_user_by_account(username)
        if ret is not None:
            raise serializers.ValidationError("对不起，该用户名已经被注册")

        return attrs

    def create(self, validated_data):
        # 加密密码
        raw_password = validated_data.get("password")
        hash_password = make_password(raw_password)
        # 设置用户名默认值
        username = validated_data.get("username")
        # 调用序列化器提供的create方法
        user = User.objects.create(
            username=username,
            password=hash_password,
        )
        refresh = TokenObtainPairSerializer.get_token(user)
        # 手动生成token的方法生成登录状态
        user.token = str(refresh.access_token)

        return user


class MyTokenObtainPairSerializer(TokenObtainPairSerializer):

    def validate(self, attrs):
        data = super().validate(attrs)
        refresh = self.get_token(self.user)
        data['refresh'] = str(refresh)
        data['access'] = str(refresh.access_token)
        data["stated"] = self.user.is_superuser
        data['username'] = self.user.username
        data['id'] = self.user.id
        return data


class UserSetSerializer(serializers.ModelSerializer):
    """
    用户设置序列化器
    """

    class Meta:
        model = User
        fields = '__all__'


class UserUploadSerializers(serializers.ModelSerializer):
    """
    用户头像上传序列化器
    """

    class Meta:
        model = User
        fields = ['id', 'avatar']
